package com.agileplex.products.acc.commands;

import java.util.List;
import java.util.ArrayList;

/**
 * LexicalParser
 *
 * @creator Rui Tang
 * @date 2008-06-22
 *
 * @LastChanged
 * @LastChangedBy $LastChangedBy: tangrui@agileplex.com $
 * @LastChangedDate $LastChangedDate: 2008-06-22 16:08:49 +0000 (Sun, 22 Jun 2008) $
 * @LastChangedRevision $LastChangedRevision: 7 $
 */
public class LexicalParser {

    private String text;
    private List<String> tokens = new ArrayList<String>();
    private int index = 0;

    public LexicalParser(String text) {
        this.text = text;
        this.parse();
    }

    private void parse() {
        boolean tokenStart = false;
        StringBuffer sb = null;

        for (int i = 0; i < this.text.length(); i++) {
            char ch = this.text.charAt(i);
            if (Character.isWhitespace(ch)) {
                if (tokenStart) {
                    tokenStart = false;
                    tokens.add(sb.toString());
                }
            } else {
                if (!tokenStart) {
                    tokenStart = true;
                    sb = new StringBuffer();
                }
                sb.append(ch);
            }
        }
        if (tokenStart) {
            this.tokens.add(sb.toString());
        }
    }

    public String[] toTokenArray() {
        List<String> subList = this.tokens.subList(this.index, this.tokens.size());

        return (String[])subList.toArray();
    }

    public String getNextToken() {
        if (this.index >= this.tokens.size()) {
            return null;
        }

        return this.tokens.get(this.index++);
    }

}
